<template>
  <div class="parking-add">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
        </div>
      </template>
      <div class="form-container">
        <el-form
          :model="parkingForm"
          :rules="rules"
          ref="parkingFormRef"
          label-width="120px"
          :disabled="loading"
          v-loading="loading"
        >
          <el-form-item label="所属小区" prop="community.id">
            <el-select v-model="parkingForm.community.id" placeholder="请选择小区">
              <el-option 
                v-for="item in communities" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车位编号" prop="code">
            <el-input v-model="parkingForm.code" placeholder="请输入车位编号"></el-input>
          </el-form-item>
          <el-form-item label="车位名称" prop="name">
            <el-input v-model="parkingForm.name" placeholder="请输入车位名称"></el-input>
          </el-form-item>
          <el-form-item label="车位类型" prop="type">
            <el-select v-model="parkingForm.type" placeholder="请选择车位类型">
              <el-option label="地上车位" value="地上车位"></el-option>
              <el-option label="地下车位" value="地下车位"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车位面积" prop="area">
            <el-input-number v-model="parkingForm.area" :min="0" :precision="2" :step="0.5"></el-input-number>
            <span class="unit">m²</span>
          </el-form-item>
          <el-form-item label="使用状态" prop="status">
            <el-select v-model="parkingForm.status" placeholder="请选择使用状态">
              <el-option label="闲置中" value="闲置中"></el-option>
              <el-option label="已售出" value="已售出"></el-option>
              <el-option label="已出租" value="已出租"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="parkingForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'ParkingAdd',
  data() {
    return {
      formTitle: '添加车位',
      loading: false,
      submitting: false,
      communities: [],
      parkingForm: {
        id: null,
        community: {
          id: ''
        },
        code: '',
        name: '',
        type: '',
        area: 0,
        status: '闲置中',
        remarks: ''
      },
      rules: {
        'community.id': [
          { required: true, message: '请选择所属小区', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入车位编号', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入车位名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择车位类型', trigger: 'change' }
        ],
        area: [
          { required: true, message: '请输入车位面积', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择使用状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    // 加载小区列表
    this.fetchCommunities();
    
    // 如果是编辑，则获取ID并加载数据
    const id = this.$route.query.id;
    if (id) {
      this.formTitle = '编辑车位';
      this.loadParkingData(id);
    }
  },
  methods: {
    // 获取小区列表
    async fetchCommunities() {
      try {
        this.loading = true;
        const response = await axios.get('/api/communities');
        this.communities = response.data;
      } catch (error) {
        console.error('Failed to fetch communities:', error);
        ElMessage.error('获取小区列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 加载车位数据
    async loadParkingData(id) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/parkings/${id}`);
        this.parkingForm = response.data;
        
        // 确保community对象存在
        if (!this.parkingForm.community) {
          this.parkingForm.community = { id: '' };
        }
      } catch (error) {
        console.error('Failed to load parking data:', error);
        ElMessage.error('加载车位数据失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.parkingFormRef.validate();
        if (!valid) {
          ElMessage.error('表单验证失败，请检查必填项');
          return;
        }
        
        this.submitting = true;
        
        // 准备提交的数据
        const parkingData = {
          ...this.parkingForm,
          // 确保community对象格式正确
          community: {
            id: this.parkingForm.community.id
          }
        };
        
        if (this.parkingForm.id) {
          // 更新车位
          await axios.put(`/api/parkings/${this.parkingForm.id}`, parkingData);
          ElMessage.success('编辑成功');
        } else {
          // 添加车位
          await axios.post('/api/parkings', parkingData);
          ElMessage.success('添加成功');
        }
        
        // 返回列表页
        this.goBack();
      } catch (error) {
        console.error('Failed to submit form:', error);
        ElMessage.error(error.response?.data?.message || '提交失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    },
    
    goBack() {
      this.$router.push('/property/parking');
    }
  }
};
</script>

<style scoped>
.parking-add {
  padding: 20px;
}
.form-container {
  max-width: 800px;
  margin: 0 auto;
}
.unit {
  margin-left: 10px;
}
</style>
